package com.juzhi.dvrapp.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.juzhi.dvrapp.R;
import com.juzhi.dvrapp.bean.Device;
import com.juzhi.dvrapp.bean.HttpGetDeviceInfoResponse;
import com.juzhi.dvrapp.callback.JsonCallback;
import com.juzhi.dvrapp.manager.AppManager;
import com.juzhi.dvrapp.utils.Config;
import com.juzhi.dvrapp.utils.MLog;
import com.juzhi.dvrapp.utils.Urls;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;

/**
 * Created by YangHu on 2017/8/30.
 */

public abstract class BaseAcitivity extends AppCompatActivity {

    protected ImageView backItem;
    protected TextView titleItem;
    protected ImageView functionItem;
    protected Bundle savedInstanceState;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);

        this.savedInstanceState = savedInstanceState;
        initView();

    }

    protected void registEventBus() {
        //子类如果需要注册eventbus，则重写此方法
        EventBus.getDefault().register(this);
    }

    protected void unRegistEventBus() {
        //子类如果需要注销eventbus，则重写此方法
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        AppManager.getAppManager().finishActivity(this);
    }

    protected Bundle getSavedInstanceState(){
        return savedInstanceState;
    }

    /**
     * 初始化头控件
     */
    protected void initHeaderView()
    {
        backItem = (ImageView)findViewById(R.id.back_item);
        titleItem = (TextView)findViewById(R.id.title_item);
        functionItem =(ImageView)findViewById(R.id.fun_item);

        backItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                back();
            }
        });

        functionItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                 function();
            }
        });
    }

    /**
     * 返回按钮事件 默认情况下是返回前一个Activity
     */
    protected void back() {
        finish();
    }

    /**
     * 右上角功能按钮事件
     */
    protected void function()
    {}

    /**
     * 右上角设置图片
     */
    protected void setFunctionImg(Drawable drawable){
        functionItem.setImageDrawable(drawable);
    }

    /**
     * 设置标题
     */
    protected void setTitleText(String text)
    {
        titleItem.setText(text);
    }


    public String getStringText(int stringID)
    {
        return this.getResources().getString(stringID);
    }

    protected void hideFunction()
    {
        functionItem.setVisibility(View.INVISIBLE);
    }

    protected void hideBack(){
        backItem.setVisibility(View.INVISIBLE);
    }

    //强制关闭软键盘

    public void closeKeyboard(){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            MLog.i("按下了屏幕------");
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, event)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.onTouchEvent(event);

    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText || v instanceof TextInputLayout)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    public void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public abstract int getLayoutId();

    protected abstract void initView();

    public void getDeviceInfo(final Device device) {
        OkGo.<HttpGetDeviceInfoResponse>get(Urls.URL_CMS_GET_DEVICE_INFO)
                .tag(this)
                .removeAllParams()
                .params(Config.DEVICE, device.getDeviceModel().getSsid())
                .execute(new JsonCallback<HttpGetDeviceInfoResponse>() {

                    @Override
                    public void onSuccess(Response<HttpGetDeviceInfoResponse> response) {
                        HttpGetDeviceInfoResponse.EasyDarwinBean easyDarwin = response.body().getEasyDarwin();
                        if (easyDarwin.getHeader().getErrorNum().equals(Config.RESULT_CMS_SUCCESS)) {
                            device.setStatus(Config.DEVICE_RESULT_SUCCESS);
                            device.setDeviceSnap(easyDarwin.getBody().getSnapURL());

                            Intent intent = new Intent(BaseAcitivity.this, DeviceInfoActivity.class);
                            intent.putExtra(Config.SSID, device.getDeviceModel().getSsid());
                            startActivity(intent);
                            finish();
                        } else {
                            device.setStatus(Config.DEVICE_RESULT_OFFLINE);
                            if (!AppManager.getAppManager().currentActivity().getLocalClassName().equals(MainActivity.class.getName())){
                                Intent intent = new Intent(BaseAcitivity.this, MainActivity.class);
                                startActivity(intent);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<HttpGetDeviceInfoResponse> response) {
                        super.onError(response);
                        Intent intent = new Intent(BaseAcitivity.this, MainActivity.class);
                        startActivity(intent);
                    }
                });
    }
}
